import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout.vue'
import store from '@/store/index.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    // 返回的就是import进来的组件
    // 组件懒加载：只有在访问这个路由时，才会去加载这个组件
    component: () => import('../views/login/index.vue')
  },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', name: 'Home', component: () => import('../views/home/index.vue') },
      { path: '/question', name: 'Question', component: () => import('../views/question/index.vue') },
      { path: '/video', name: 'Video', component: () => import('../views/video/index.vue') },
      { path: '/user', name: 'User', component: () => import('../views/user/index.vue') }
    ]
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('../views/search/index.vue')
  },
  {
    path: '/search/result',
    name: 'searchResult',
    component: () => import('../views/search/result.vue')
  },
  {
    path: '/article/:id',
    name: 'articleDetail',
    component: () => import('../views/article/index.vue')
  },
  {
    // 编辑资料
    path: '/user/profile',
    name: 'userProfile',
    component: () => import('../views/user/profile.vue')
  },
  {
    // 聊天机器人
    path: '/user/chat',
    name: 'userChat',
    component: () => import('../views/user/chat.vue')
  }

]

const router = new VueRouter({
  routes
})

// 导航守卫
// 路由变化时执行
// 在跳入到目标路由之前会执行
// to 去哪
// from 从哪
// next 函数，做路由跳转
router.beforeEach(function (to, from, next) {
  if (isOk(to)) {
    next()
  } else {
    next({
      path: '/login',
      query: {
        from: to.fullPath //  /-%2F
      }
    })
  }
})

function isOk (to) {
  if (to.path.startsWith('/user') && !store.state.user) {
    return false
  } else {
    return true
  }
}

export default router
